﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using web.core.Models;
using web.core.ViewModels;
using System.Web.UI;
using System.Xml;
using iTextSharp.text;
using iTextSharp.text.xml;
using iTextSharp.text.pdf;
using System.IO;
using System.Text;

namespace web.core.Controllers
{
    public class baseController : Controller
    {

        public string ControllerName
        {
            get
            {
                return Url.RequestContext.RouteData.Values["controller"].ToString();
            }
        }

        public string ActionName
        {
            get
            {
                return Url.RequestContext.RouteData.Values["action"].ToString();
            }
        }

        public string ParentActionName
        {
            get
            {
                return ControllerContext.ParentActionViewContext.RouteData.Values["action"].ToString();
            }
        }

        public void InitPage()
        {
            ////check quyền tại đây
            if (Session["user_id"] != null)
            {
                int user_id = int.Parse(Session["user_id"].ToString());
                string path = "/" + ControllerName + "/" + ActionName;
                if (Models.accountModels.checkPageAccessByUser(user_id, path))
                {
                    ViewBag.permission = true;
                }
                else
                {
                    ViewBag.permission = false;// "You do not have permission to access...";
                }
            }
            else
            {
                RedirectToAction("login", "account");
            }
        }

        public bool isNumber(string val)
        {
            int Num;
            bool isNum = int.TryParse(val, out Num);
            if (isNum)
                return true;
            else
                return false;
        }

        public string DefaultHostGetter()
        {
            string host = this.Request.Url.Host;
            if (host.Contains("www."))
            {
                host = host.Replace("www.", "");
            }
            return host;
        }

        public string DefaultLanguageGetter()
        {
            var arr = this.Request.Url.PathAndQuery.Split('/');
            if (this.Request.Url.PathAndQuery.Contains("Rejected-By-UrlScan?~"))
            {
                arr = this.Request.Url.PathAndQuery.Replace("/Rejected-By-UrlScan?~", "").Split('/');
                return arr[0];
            }
            else
                return arr[1];
            
        }

        /// <summary>
        /// Renders an action result to a string. This is done by creating a fake http context
        /// and response objects and have that response send the data to a string builder
        /// instead of the browser.
        /// </summary>
        /// <param name="result">The action result to be rendered to string.</param>
        /// <returns>The data rendered by the given action result.</returns>
        protected string RenderActionResultToString(ActionResult result)
        {
            // Create memory writer.
            var sb = new StringBuilder();
            var memWriter = new StringWriter(sb);

            // Create fake http context to render the view.
            var fakeResponse = new HttpResponse(memWriter);
            var fakeContext = new HttpContext(System.Web.HttpContext.Current.Request, fakeResponse);
            var fakeControllerContext = new ControllerContext(
                new HttpContextWrapper(fakeContext),
                this.ControllerContext.RouteData,
                this.ControllerContext.Controller);
            var oldContext = System.Web.HttpContext.Current;
            System.Web.HttpContext.Current = fakeContext;

            // Render the view.
            result.ExecuteResult(fakeControllerContext);

            // Restore data.
            System.Web.HttpContext.Current = oldContext;

            // Flush memory and return output.
            memWriter.Flush();
            return sb.ToString();
        }

        /// <summary>
        /// Returns a PDF action result. This method renders the view to a string then
        /// use that string to generate a PDF file. The generated PDF file is then
        /// returned to the browser as binary content. The view associated with this
        /// action should render an XML compatible with iTextSharp xml format.
        /// </summary>
        /// <param name="model">The model to send to the view.</param>
        /// <returns>The resulted BinaryContentResult.</returns>
        protected ActionResult ViewPdf(object model)
        {
            // Create the iTextSharp document.
            Document doc = new Document();
            // Set the document to write to memory.
            MemoryStream memStream = new MemoryStream();
            PdfWriter writer = PdfWriter.GetInstance(doc, memStream);
            writer.CloseStream = false;
            doc.Open();

            // Render the view xml to a string, then parse that string into an XML dom.
            string xmltext = this.RenderActionResultToString(this.View(model));
            XmlDocument xmldoc = new XmlDocument();
            xmldoc.InnerXml = xmltext.Trim();

            // Parse the XML into the iTextSharp document.
            ITextHandler textHandler = new ITextHandler(doc);
            textHandler.Parse(xmldoc);

            // Close and get the resulted binary data.
            doc.Close();
            byte[] buf = new byte[memStream.Position];
            memStream.Position = 0;
            memStream.Read(buf, 0, buf.Length);

            // Send the binary data to the browser.
            return new BinaryContentResult(buf, "application/pdf");
        }

        [ChildActionOnly]
        public ActionResult control_header()
        {
            var header_view = new ViewModels.MenuViewModels();
            header_view.listTopParentPage = accountModels.getListTopPageParent(int.Parse(Session["user_id"].ToString()));
            header_view.controller_name = ControllerName;
            header_view.total_male = accountModels.getTotalMaleEmployee();
            header_view.total_female = accountModels.getTotalFemaleEmployee();
            return PartialView("../Shared/control_header", header_view);
        }

        [ChildActionOnly]
        public ActionResult control_leftmenu_account()
        {   //account page id=3
            var header_view = new ViewModels.MenuViewModels();
            header_view.tw = accountModels.getListPageMenuBuilder(3, int.Parse(Session["user_id"].ToString()), Request.Url.ToString());
            header_view.controller_name = ControllerName;
            return PartialView("../Shared/control_leftmenu_account", header_view);
        }

        [ChildActionOnly]
        public ActionResult control_leftmenu_dashboard()
        {   //dashboard page id=1
            var header_view = new ViewModels.MenuViewModels();
            header_view.tw = accountModels.getListPageMenuBuilder(1, int.Parse(Session["user_id"].ToString()), Request.Url.ToString());
            header_view.controller_name = ControllerName;
            return PartialView("../Shared/control_leftmenu_dashboard", header_view);
        }

        [ChildActionOnly]
        public ActionResult control_leftmenu_content()
        {   //content page id=17
            var header_view = new ViewModels.MenuViewModels();
            header_view.tw = accountModels.getListPageMenuBuilder(17, int.Parse(Session["user_id"].ToString()), Request.Url.ToString());
            header_view.controller_name = ControllerName;
            return PartialView("../Shared/control_leftmenu_content", header_view);
        }

        [ChildActionOnly]
        public ActionResult control_leftmenu_profile()
        {   //profile page id=33
            var header_view = new ViewModels.MenuViewModels();
            header_view.tw = accountModels.getListPageMenuBuilder(33, int.Parse(Session["user_id"].ToString()), Request.Url.ToString());
            header_view.controller_name = ControllerName;
            return PartialView("../Shared/control_leftmenu_profile", header_view);
        }
    }
}
